package com.example.modulejsonui.util

import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import com.example.customview.bean.LayoutBean
import com.example.customview.util.DrawableUtil

/**
 * Created by Android Studio.
 * User: wsl
 * Date: 8/18/21
 * Time: 11:39 AM
 * Description:
 */
class ItemLayoutUtil {
    companion object instance {

        /**
         * 获取传入指定视图下的所有子视图
         *
         * @param view
         * @return
         */
        fun getAllChildViews(view: View?): List<View>? {
            val allChildViews: MutableList<View> = ArrayList()
            if (view != null && view is ViewGroup) {
                val vp = view
                for (i in 0 until vp.childCount) {
                    val viewChild = vp.getChildAt(i)
                    // 添加视图
                    allChildViews.add(viewChild)
                    // 方法递归
                    allChildViews.addAll(getAllChildViews(viewChild)!!)
                }
            }
            return allChildViews
        }


        fun RankingItemView(constraint: RelativeLayout, view: View, layout: LayoutBean){
            var viewList =    getAllChildViews(constraint)
            if(viewList?.size == 0){
                val rlp = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
                rlp.setMargins(layout.left,layout.top,layout.right,layout.bottom)
                DrawableUtil
//                view.setPadding(DrawableUtil.dp2px(context, textbean.layout.left.toFloat()), DrawableUtil.dp2px(context, textbean.layout.top.toFloat()),
//                        DrawableUtil.dp2px(context, textbean.layout.right.toFloat()), DrawableUtil.dp2px(context, textbean.layout.bottom.toFloat()))
                constraint.addView(view,rlp)
            }else{
                var views = viewList?.get(viewList.size -1)
                val rlp = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
                rlp.setMargins(layout.left,layout.top,layout.right,layout.bottom)
                if(layout.isLeftRelative){
                    rlp.addRule(RelativeLayout.LEFT_OF,views!!.id)
//                    rlp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
                } else if(layout.isTopRelative){
                    rlp.addRule(RelativeLayout.ABOVE,views!!.id)
                } else if(layout.isBottomRelative){
                    rlp.addRule(RelativeLayout.BELOW,views!!.id)
//                    rlp.addRule(RelativeLayout.ALIGN_LEFT, views!!.id);
                } else if(layout.isRightRelative){
                    rlp.addRule(RelativeLayout.RIGHT_OF,views!!.id)
//                    rlp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
                }
                constraint.addView(view,rlp)

            }
        }
    }
}